package com.xinlin.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson2.JSONObject;
import com.xinlin.common.filter.RepeatedlyRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper;
import org.springframework.util.StreamUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.xinlin.common.constant.Constants;
import com.xinlin.common.core.text.Convert;

/**
 * 客户端工具类
 *
 * @author xinlin
 */
@Slf4j
public class ServletUtils {
    /**
     * 获取String参数
     */
    public static String getParameter(String name) {
        return getRequest().getParameter(name);
    }

    /**
     * 获取String参数
     */
    public static String getParameter(String name, String defaultValue) {
        return Convert.toStr(getRequest().getParameter(name), defaultValue);
    }

    /**
     * 获取Integer参数
     */
    public static Integer getParameterToInt(String name) {
        return Convert.toInt(getRequest().getParameter(name));
    }

    /**
     * 获取Integer参数
     */
    public static Integer getParameterToInt(String name, Integer defaultValue) {
        return Convert.toInt(getRequest().getParameter(name), defaultValue);
    }

    /**
     * 获取Boolean参数
     */
    public static Boolean getParameterToBool(String name) {
        return Convert.toBool(getRequest().getParameter(name));
    }

    /**
     * 获取Boolean参数
     */
    public static Boolean getParameterToBool(String name, Boolean defaultValue) {
        return Convert.toBool(getRequest().getParameter(name), defaultValue);
    }

    /**
     * 获得所有请求参数
     *
     * @param request 请求对象{@link ServletRequest}
     * @return Map
     */
    public static Map<String, String[]> getParams(ServletRequest request) {
        final Map<String, String[]> map = request.getParameterMap();
        return Collections.unmodifiableMap(map);
    }

    /**
     * 获得所有请求参数
     *
     * @param request 请求对象{@link ServletRequest}
     * @return Map
     */
    public static Map<String, String> getParamMap(ServletRequest request) {
        Map<String, String> params = new HashMap<>();
        for (Map.Entry<String, String[]> entry : getParams(request).entrySet()) {
            params.put(entry.getKey(), StringUtils.join(entry.getValue(), ","));
        }
        return params;
    }

    /**
     * 获取request中body中的内容，并转化成map
     *
     * @param request HttpServletRequest
     * @param ignores 忽略字段
     * @return
     */
    public static Map<String, String> getBodyContext(HttpServletRequest request, String... ignores) throws IOException {

        if (ObjectUtils.isEmpty(request)) {
            log.error("传入的request为空!");
            throw new IllegalArgumentException("传入的request为空!");
        }
        StringBuffer sbBodyContext = new StringBuffer();

        try {
            if (request instanceof RepeatedlyRequestWrapper) {
                RepeatedlyRequestWrapper bufferedServletRequestWrapper = (RepeatedlyRequestWrapper) request;
                ServletInputStream requestInput = bufferedServletRequestWrapper.getInputStream();

                BufferedReader reader = new BufferedReader(new InputStreamReader(requestInput));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sbBodyContext.append(line);
                }
            } else if (request instanceof SecurityContextHolderAwareRequestWrapper) {
                sbBodyContext.append(getRequestBody((SecurityContextHolderAwareRequestWrapper) request));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        String bodyContext = sbBodyContext.toString();
        if (StringUtils.isBlank(bodyContext)) {
            return null;
        }

        Map<String, String> result = new HashMap<>();

        Map stringToMap = JSONObject.parseObject(bodyContext);
        Iterator<Map.Entry> it = stringToMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = it.next();
            // 去除忽略部分
            if (ObjectUtils.isNotEmpty(ignores) && ignores.length > 0) {
                boolean isIgnore = false;
                for (String ignore : ignores) {
                    if (StringUtils.equals(entry.getKey() + "", ignore)) {
                        isIgnore = true;
                        log.info("已经忽略{}字段", ignore);
                        break;
                    }
                }
                if (isIgnore) {
                    continue;
                }
            }
            Object key = entry.getKey();
            Object value = entry.getValue();
            if (ObjectUtils.isNotEmpty(key) && ObjectUtils.isNotEmpty(value)) {
                result.put(entry.getKey() + "", entry.getValue() + "");
                log.info("key = {}, value = {}", key, value);
            }
        }
        return result;
    }


    public static String getRequestBody(SecurityContextHolderAwareRequestWrapper requestWrapper) {
        try {
            // 获取请求的 InputStream 并读取 Body
            return StreamUtils.copyToString(
                    requestWrapper.getInputStream(),
                    StandardCharsets.UTF_8
            );
        } catch (Exception e) {
            throw new RuntimeException("Failed to read request body", e);
        }
    }

    /**
     * @param request
     * @return
     */
    public static Map<String, String> getParameterMap(HttpServletRequest request) {
        if (ObjectUtils.isEmpty(request)) {
            log.error("传入的request为空!");
            throw new IllegalArgumentException("传入的request为空!");
        }
        Map<String, String[]> parameterMap = request.getParameterMap();
        if (ObjectUtils.isEmpty(parameterMap)) {
            return null;
        }
        Map<String, String> result = new HashMap<String, String>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey();
            String value = null;
            String[] values = entry.getValue();
            if (values != null && values.length > 0) {
                value = values[0];
            }
            if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(value)) {
                result.put(key, value);
                log.info("key = {}, value = {}", key, value);
            }
        }

        return result;
    }

    public static String getHeaderVal(String key) {
        return getRequest().getHeader(key);
    }

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取response
     */
    public static HttpServletResponse getResponse() {
        return getRequestAttributes().getResponse();
    }

    /**
     * 获取session
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    public static ServletRequestAttributes getRequestAttributes() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }

    /**
     * 将字符串渲染到客户端
     *
     * @param response 渲染对象
     * @param string   待渲染的字符串
     */
    public static void renderString(HttpServletResponse response, String string) {
        try {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 是否是Ajax异步请求
     *
     * @param request
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String accept = request.getHeader("accept");
        if (accept != null && accept.contains("application/json")) {
            return true;
        }

        String contentType = request.getHeader("content-type");
        if (contentType != null && contentType.contains("application/json")) {
            return true;
        }

        String xRequestedWith = request.getHeader("X-Requested-With");
        if (xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest")) {
            return true;
        }

        String uri = request.getRequestURI();
        if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml")) {
            return true;
        }

        String ajax = request.getParameter("__ajax");
        return StringUtils.inStringIgnoreCase(ajax, "json", "xml");
    }

    /**
     * 内容编码
     *
     * @param str 内容
     * @return 编码后的内容
     */
    public static String urlEncode(String str) {
        try {
            return URLEncoder.encode(str, Constants.UTF8);
        } catch (UnsupportedEncodingException e) {
            return StringUtils.EMPTY;
        }
    }

    /**
     * 内容解码
     *
     * @param str 内容
     * @return 解码后的内容
     */
    public static String urlDecode(String str) {
        try {
            return URLDecoder.decode(str, Constants.UTF8);
        } catch (UnsupportedEncodingException e) {
            return StringUtils.EMPTY;
        }
    }
}
